package com.example.administrator.androidapp;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class Ch10Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_ch10);


    }

    public void query(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);//实例化SqliteOpenHelper
        SQLiteDatabase sqLiteDatabase=myDbHelper.getReadableDatabase();//打开数据库
        //Cursor cursor=sqLiteDatabase.query("student",new String[]{"stuid,stuname"},"stuid=?",new String[]{"1"},null,null,null);
        Cursor cursor=sqLiteDatabase.query("student",new String[]{"stuid,stuname"},null,null,null,null,null);
        while (cursor.moveToNext()){//每次指向新的一条记录，直至最后
            int index=cursor.getColumnIndex("stuid");//得到列的索引
            int stuid=cursor.getInt(index);
            index=cursor.getColumnIndex("stuname");
            String stuname=cursor.getString(index);
            Log.i(Ch10Activity.class.toString(),"stuid:"+stuid+",stuname:"+stuname);
        }
        cursor.close();
        sqLiteDatabase.close();//关闭数据库
    }

    public void insert(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);//实例化SqliteOpenHelper
        SQLiteDatabase sqLiteDatabase=myDbHelper.getWritableDatabase(); //打开数据库
        sqLiteDatabase.execSQL("insert into student(stuname,height)values(?,?)",new String[]{"Tom","181"});
        sqLiteDatabase.close();//关闭数据库
    }
    public void delete(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);//实例化SqliteOpenHelper
        SQLiteDatabase sqLiteDatabase=myDbHelper.getWritableDatabase(); //打开数据库
        sqLiteDatabase.delete("student","stuid=?",new String[]{"1"});
        sqLiteDatabase.close();//关闭数据库
    }

    public void modify(View view){
        MyDbHelper myDbHelper=new MyDbHelper(this);//实例化SqliteOpenHelper
        SQLiteDatabase sqLiteDatabase=myDbHelper.getWritableDatabase(); //打开数据库
        ContentValues contentValues=new ContentValues();//将记录的内容放入
        contentValues.put("stuname","Mike");
        sqLiteDatabase.update("student",contentValues,"stuid=?",new String[]{"2"});
        sqLiteDatabase.close();//关闭数据库
    }

}
